﻿using Abp;
using Castle.Core.Logging;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Messaging;
using System.Text;
using System.Threading.Tasks;
using Abp.Dependency;

namespace Abp.MSMQ
{
    public class MessageManager
    {
        static MessageQueue queue;


        static ILogger logger;
        public static void Initialize(bool flag, params Type[] messageTypes)
        {
            logger = ObjectContainer.Resolve<ILogger>();
            string path = ConfigurationManager.AppSettings["MessageQueue"];
            if (string.IsNullOrWhiteSpace(path))
                path = @".\Private$\tmrs";
            if (MessageQueue.Exists(path))
            {
                queue = new MessageQueue(path);
            }
            else
            {
                queue = MessageQueue.Create(path, false);
            }

            queue.SetPermissions("everyone", MessageQueueAccessRights.FullControl);
            queue.Formatter = new XmlMessageFormatter(messageTypes);


            if (flag)
            {
                queue.BeginPeek();
                queue.PeekCompleted += Queue_PeekCompleted;
            }

        }

        private static void Queue_PeekCompleted(object sender, PeekCompletedEventArgs e)
        {
            Message message = queue.Receive();
            string label = message.Label;
            IMessageHandler handler = ObjectContainer.ResolveNamed<IMessageHandler>(label);
            try
            {
                logger.Info(label);
                handler.Handle(message.Body);

            }
            catch (Exception ex)
            {
                logger.Error(ex.Message, ex);
                //数据库异常，重新入队
                SendMessage(label, message.Body);
            }
            
            queue.BeginPeek();

        }

        public static void SendMessage(string label, object body)
        {
            queue.Send(body, label);
        }


    }


}
